<?php 

defined('_JEXEC') or die('Restricted access');

JFormHelper::loadFieldClass('groupedlist');

class JFormFieldDoskacat extends JFormFieldGroupedList {
	
	protected $type='Doskacat';
	
	protected function getGroups() {
		
		
		$parent  = parent::getGroups();
		
		
		
		$db = JFactory::getDbo();
		$query = $db->getQuery(TRUE);
		
		$query->select('id AS value, name AS text,parentid'); 
		$query->from('#__doska_categories AS a');
		$query->where('state = 1');
		
		$db->setQuery($query);
		
		try {
			$row = $db->loadObjectList();
		}
		catch(RuntimeException $e) {
			JFactory::getApplication()->enqueueMessage($e->getMessage(),'error');
			return false;
		}
		
		$arr = array();
		
		foreach($parent as $option) {
			array_push($arr,$option);
		}
		
		
		if($row) {
			
			$options = array();
			
			for($i = 0; $i < count($row);$i++) {
				
				if($row[$i]->parentid == 0) {
					if(!$options[$row[$i]->value]) {
						$options[$row[$i]->value] = $row[$i];
					}
					else {
						$options[$row[$i]->value]->value = $row[$i]->value;
						$options[$row[$i]->value]->text = $row[$i]->text;
					}
				}
				else {
					$options[$row[$i]->parentid]->items[] = $row[$i];
				}
			}
			
			
			foreach($options as $key=>$opt) {
				if(!isset($opt->items) || count($opt->items) == 0) {
					unset($options[$key]);
				}
				if(isset($opt->text)) {
					$arr[$opt->text] = $opt->items;
				}
			}
		}
		
		
		
		return $arr;
		
	}
	
}